package com.alingrad.android.froyoengine.graphics.renderable;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import com.alingrad.android.froyoengine.collisions.CollisionMaskData;
import com.alingrad.android.froyoengine.graphics.Texture;
import com.alingrad.android.froyoengine.util.GLHelper;

public class Sprite extends Rectangle {
	private Texture mTexture;
	private FloatBuffer mTextureBuffer;
	
	public Sprite(Texture texture) {
		super(texture.mWidth, texture.mHeight);
		mTexture = texture;
		float[] textures = new float[8]; {
			textures[0] = 0f;
			textures[1] = 0f;
			textures[2] = 0f;
			textures[3] = 1f;
			textures[4] = 1f;
			textures[5] = 1f;
			textures[6] = 1f;
			textures[7] = 0f;
		}
		ByteBuffer bb = ByteBuffer.allocateDirect(textures.length * 4);
		bb.order(ByteOrder.nativeOrder());
		mTextureBuffer = bb.asFloatBuffer();
		mTextureBuffer.put(textures);
		mTextureBuffer.position(0);
	}
	
	@Override
	public void draw(GL10 gl, float x, float y, float z, float scaleX, float scaleY, float rotation) {
		gl.glPushMatrix();
			GLHelper.setMatrix(gl, x, y, z, scaleX, scaleY, rotation);
			mTexture.bind(gl);
			gl.glEnable(GL10.GL_TEXTURE_2D);
			gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
			gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
			gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
			gl.glDrawElements(GL10.GL_TRIANGLES, mIndexBuffer.capacity(), GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
			gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
			gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
			gl.glDisable(GL10.GL_TEXTURE_2D);
		gl.glPopMatrix();
	}
	
	@Override
	public CollisionMaskData getCollisionMaskData() {
		return mTexture.mData;
	}
}
